package epoch.game.core.message;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

import epoch.game.core.serialize.ISerializable;
import epoch.game.core.serialize.IStreamReader;
import epoch.game.core.serialize.IStreamWriter;
import epoch.game.core.server.ISession;

public class WrappedMessage implements IMessage, ISerializable{
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 3495415494616181750L;
	//消息id
	private short id;
	//发送者
	private long sender;
	//接收者
	private List<Long> receivers = new LinkedList<Long>();
	//消息数据
	private byte[] msgData;
	//session
	private ISession session;
	//参数
	private Object param;
	
	@Override
	public short getId() {
		return id;
	}

	public void setId(short id) {
		this.id = id;
	}

	public long getSender() {
		return sender;
	}

	public void setSender(long sender) {
		this.sender = sender;
	}

	public List<Long> getReceivers() {
		return receivers;
	}

	public void setReceivers(List<Long> receivers) {
		this.receivers = receivers;
	}

	public byte[] getMsgData() {
		return msgData;
	}

	public void setMsgData(byte[] msgData) {
		this.msgData = msgData;
	}

	public int getLength() {
		return this.msgData.length + 2;
	}

	public int getLengthWithRole() {
		return this.msgData.length + 2 + 8 + this.receivers.size() * 8 + 4;
	}

	public ISession getSession() {
		return session;
	}

	public void setSession(ISession session) {
		this.session = session;
	}

	@SuppressWarnings("unchecked")
	@Override
	public <T> T getParameter() {
		return (T)param;
	}

	@Override
	public <T> void setParameter(T param) {
		this.param = param;
	}

	@Override
	public String getQueue() {
		return null;
	}

	@Override
	public String getServer() {
		return null;
	}
	
	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();
		sb.append("class=WrappedMessage").append(",id=").append(id).append(",sender=").append(sender).append(",receivers=[");
		if (receivers != null && !receivers.isEmpty()) {
			int size = receivers.size();
			int limit = size>5 ? 5 : size;
			for (int i = 0; i < limit; i++) {
				sb.append(receivers.get(i)).append(",");
			}
			if(size>5){
				sb.append("...");
			}
			sb.append("]");
		}
		return sb.toString();
	}

	@Override
	public void readFrom(IStreamReader reader) throws IOException {
		this.id = reader.readShort();
		this.sender = reader.readLong();
		this.receivers = reader.read();
		this.msgData = reader.readBytes();
	}

	@Override
	public void writeTo(IStreamWriter writer) throws IOException {
		writer.writeShort(this.id);
		writer.writeLong(this.sender);
		writer.write(this.receivers);
		writer.writeBytes(this.msgData);
	}
}
